

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <thread>
#include "utilitys.h"

template <class T>
T *CreateConsSharMemory(int nKey, int &shmID)

{
    // 创建共享内存
    shmID = shmget(nKey, 0, 0);
    if (shmID < 0)
    {
        // todo 输出log 共享内存创建失败
        std::cerr << "shmget fail, " << errno << std::endl;
        return nullptr;
    }

    // 映射共享内存到进程地址空间
    T *pDataField = (T *)shmat(shmID, 0, 0);
    if (((void *)(-1)) == (void *)pDataField)
    {
        // 映射失败
        std::cerr << "shmat failed: " << errno << std::endl;
        perror("shmat ");
        return nullptr;
    }

    // 映射成功
    return pDataField;
}

int main()
{
    int shmID = 0;
    SharedMemory *pDataField = CreateConsSharMemory<SharedMemory>(333, shmID);
    long nReadIndex = pDataField->WriteIndex;
    long nMaxReadIndex = DATA_ARRAY_MAX_LENGTH - 1;
    int tradeId = 0;
    pDataField->Ready = true;

    while (true)
    {
        if (nReadIndex != pDataField->WriteIndex)
        {
            ++nReadIndex;
            nReadIndex &= nMaxReadIndex;
            if (pDataField->DataArray[nReadIndex].droneTradeId != tradeId + 1)
            {
                std::cout << "Error: TradeId is not continuous, droneTradeId:" << pDataField->DataArray[nReadIndex].droneTradeId << ", tradeId:" << tradeId << std::endl;
                break;
            }
            tradeId = pDataField->DataArray[nReadIndex].droneTradeId;
        }
    }

    return 0;
}